package rest.jbpm.services;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response.Status;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import rest.jbpm.JbpmService;
import rest.jbpm.wrappers.Group;
import rest.jbpm.wrappers.User;
import rest.jbpm.wrappers.lists.GroupList;
import rest.jbpm.wrappers.lists.StringList;
import rest.jbpm.wrappers.lists.UserList;
import rest.jbpm.identity.FindUsersByGroupCmd;

@Path("identity")
public class IdentityService extends JbpmService {
	
	private static Logger log = LoggerFactory.getLogger(IdentityService.class);

    @GET
	@Path("user/{id}")
	@Produces("text/xml")
	public User getUser(@PathParam("id") String userId) {

        org.jbpm.api.identity.User user = processEngine.getIdentityService()
                .findUserById(userId);

        if(user != null)
            return new User(user);
        else
            throw new WebApplicationException(Status.NOT_FOUND);		
	}
	
	
	@GET
	@Path("users")
	@Produces("text/xml")
	public UserList listUsers() {

		return new UserList(processEngine.getIdentityService().findUsers());		
	}
	
	@GET
	@Path("group/{id}")
	@Produces("text/xml")
	public Group getGroup(@PathParam("id") String groupId) {

        org.jbpm.api.identity.Group group = processEngine
                .getIdentityService().findGroupById(groupId);
        
        if(group != null)
            return new Group(group);
        else
            throw new WebApplicationException(Status.NOT_FOUND);
		
	}

	
	@GET
	@Path("user/{id}/groups/id")
	@Produces("text/xml")
	public StringList getGroupIdsByUser(@PathParam("id") String userId) {
		
		return new StringList(
				processEngine.getIdentityService().findGroupIdsByUser(userId));		
	}
	
	@GET
	@Path("user/{id}/groups")
	@Produces("text/xml")
	public GroupList getGroupsByUser(@PathParam("id") String userId) {
		
		return new GroupList(
				processEngine.getIdentityService().findGroupsByUser(userId));		
	}
	
	@GET
	@Path("user/{id}/groups/type/{type}")
	@Produces("text/xml")
	public GroupList getGroupsByUserAndType(@PathParam("id") String userId,
			@PathParam("type") String type) {

		return new GroupList(
				processEngine.getIdentityService().findGroupsByUserAndGroupType(userId,type));
	}

    @GET
	@Path("users/group/{id}")
	@Produces("text/xml")
    public UserList getUsersByGroup(@PathParam("id")String group) {

        return new UserList(processEngine
                .execute(new FindUsersByGroupCmd(group)));

    }

    
}
